require 'latlongutm'

class Shape < ActiveRecord::Base

    belongs_to :layer
    has_many :shape_attributes
    
    def load_from_shp(shp, fields)
      max = LatLongUTM::UTMXYToLatLon(shp.maxbound[0], shp.maxbound[1], 23, true)
      min = LatLongUTM::UTMXYToLatLon(shp.minbound[0], shp.minbound[1], 23, true)
      max, min = [ max, min ].map { |xy| xy.map { |c| LatLongUTM::RadToDeg(c) } }
      self.x = min[0] + (max[0] - min[0]) / 2
      self.y = min[1] + (max[1] - min[1]) / 2
      self.title = shp[self.title_attribute]
      Shape.filter_field_names(fields).each do |name, field|
        self.shape_attributes << ShapeAttribute.new(:name => name,
                                                  :value => shp[name],
                                                  :type => field[:type])
      end
    end
    
    def Shape.filter_field_names(fields)
      valid_fields = {}
      for name, field in fields
        valid_fields[name] = field unless name =~ /[^A-Za-z0-9_ ]/
      end
      valid_fields
    end
end
